<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Contracts\Validation\Validator;
use App\Utils\ApiResponse;

/**
 * WordPress分类标签查询请求验证类
 */
class TermQueryRequest extends FormRequest
{
    /**
     * 确定用户是否有权限进行此请求
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * 为Scribe文档生成提供查询参数信息
     */
    public function queryParameters(): array
    {
        return [
            'taxonomy' => [
                'description' => '分类法类型，默认为category',
                'example' => 'category',
            ],
            'hide_empty' => [
                'description' => '是否隐藏空分类，默认false',
                'example' => false,
            ],
            'parent' => [
                'description' => '父级ID，获取子分类',
                'example' => 0,
            ],
            'child_of' => [
                'description' => '获取指定分类的子分类',
                'example' => 1,
            ],
            'include' => [
                'description' => '包含的分类ID，多个用逗号分隔',
                'example' => '1,2,3',
            ],
            'exclude' => [
                'description' => '排除的分类ID，多个用逗号分隔',
                'example' => '4,5,6',
            ],
            'search' => [
                'description' => '搜索关键词',
                'example' => '技术',
            ],
            'orderby' => [
                'description' => '排序字段，支持name、count、slug、term_group',
                'example' => 'name',
            ],
            'order' => [
                'description' => '排序方向，ASC或DESC，默认ASC',
                'example' => 'ASC',
            ],
            'number' => [
                'description' => '返回数量限制，0表示不限制',
                'example' => 20,
            ],
            'offset' => [
                'description' => '偏移量',
                'example' => 0,
            ],
            'include_children' => [
                'description' => '是否包含子分类，嵌套返回',
                'example' => false,
            ],
        ];
    }

    /**
     * 获取验证规则
     */
    public function rules(): array
    {
        return [
            'taxonomy' => 'sometimes|string|max:32',
            'hide_empty' => 'sometimes|boolean',
            'parent' => 'sometimes|integer|min:0',
            'child_of' => 'sometimes|integer|min:0',
            'include' => 'sometimes|string|max:255',
            'exclude' => 'sometimes|string|max:255',
            'search' => 'sometimes|string|max:100',
            'orderby' => 'sometimes|string|in:name,count,slug,term_group',
            'order' => 'sometimes|string|in:ASC,DESC',
            'number' => 'sometimes|integer|min:0|max:1000',
            'offset' => 'sometimes|integer|min:0',
            'include_children' => 'sometimes|boolean',
        ];
    }

    /**
     * 获取验证错误的自定义消息
     */
    public function messages(): array
    {
        return [
            'taxonomy.max' => '分类法类型不能超过32个字符',
            'parent.integer' => '父级ID必须是整数',
            'parent.min' => '父级ID不能小于0',
            'child_of.integer' => '子分类ID必须是整数',
            'child_of.min' => '子分类ID不能小于0',
            'include.max' => '包含的分类ID列表不能超过255个字符',
            'exclude.max' => '排除的分类ID列表不能超过255个字符',
            'search.max' => '搜索关键词不能超过100个字符',
            'orderby.in' => '排序字段只能是name、count、slug、term_group之一',
            'order.in' => '排序方向只能是ASC或DESC',
            'number.integer' => '数量限制必须是整数',
            'number.min' => '数量限制不能小于0',
            'number.max' => '数量限制不能超过1000',
            'offset.integer' => '偏移量必须是整数',
            'offset.min' => '偏移量不能小于0',
        ];
    }

    /**
     * 处理验证失败的情况
     */
    protected function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(
            ApiResponse::error('参数验证失败', 422, 422, $validator->errors())
        );
    }

    /**
     * 构建WP_Term_Query查询参数
     */
    public function buildQueryArgs(): array
    {
        $args = [
            'taxonomy' => $this->get('taxonomy', 'category'),
            'hide_empty' => $this->boolean('hide_empty', false),
            'orderby' => $this->get('orderby', 'name'),
            'order' => strtoupper($this->get('order', 'ASC')),
        ];

        // 父级ID
        if ($this->has('parent')) {
            $args['parent'] = (int) $this->get('parent');
        }

        // 子分类查询
        if ($this->has('child_of')) {
            $args['child_of'] = (int) $this->get('child_of');
        }

        // 包含的分类ID
        if ($this->has('include')) {
            $include = $this->get('include');
            $args['include'] = is_string($include) ? array_map('intval', explode(',', $include)) : (array) $include;
        }

        // 排除的分类ID
        if ($this->has('exclude')) {
            $exclude = $this->get('exclude');
            $args['exclude'] = is_string($exclude) ? array_map('intval', explode(',', $exclude)) : (array) $exclude;
        }

        // 搜索关键词
        if ($this->has('search')) {
            $args['name__like'] = $this->get('search');
        }

        // 数量限制
        if ($this->has('number')) {
            $number = (int) $this->get('number');
            $args['number'] = $number > 0 ? $number : 0;
        }

        // 偏移量
        if ($this->has('offset')) {
            $args['offset'] = (int) $this->get('offset');
        }

        // 注意：include_children参数不直接传递给get_terms()
        // 而是在TermResource中处理，用于控制是否返回子分类数据

        return $args;
    }
}
